package cu.ds.logicalsync.fytasrealm.util;

import java.net.URL;
import java.util.HashMap;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;


/**
 * Resource Manager for Text, Images used throughout the application
 * 
 * @author r.vashira
 */
public final class Resources extends HashMap<String,Object> {
	private static final String BUNDLE_NAME = "cu.ds.logicalsync.fytasrealm.resources.messages"; //$NON-NLS-1$
	private static final String IMAGE_PREFIX = "cu/ds/logicalsync/fytasrealm/resources/images/";
	private static final String IMAGE_NOT_FOUND = IMAGE_PREFIX + "imageNotFound.jpg";
	
	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
			.getBundle(BUNDLE_NAME);
	
	/** The instance of the resources to use */
    public static Resources instance = null;

    /**
     * Create a new Resources instance, which loads all relevant
     * resources.
     */
	private Resources() {
		// Put the images for the JxtaTableTree
        put("TreeTable.PeerPresent", getIcon(IMAGE_PREFIX + "user.png"));//"PeerPresent.png"));
	}

	public static String getString(String key) {
		try {
			return RESOURCE_BUNDLE.getString(key);
		} catch (MissingResourceException e) {
			return '!' + key + '!';
		}
	}
	
	public static ResourceBundle getStrings() {
		return RESOURCE_BUNDLE;
	}
	
	/**
     * Get the instance of Resources to use 
     * 
     * @return the application wide instance of Resources 
     */
    public static synchronized Resources getInstance() {
    	if (instance == null) {
            instance = new Resources();
        }
        return instance;
    }
    
    /**
     * Get a resource as an Icon 
     *
     * @param resource the resource to retrieve
     * @return the resource as an icon or null if the resource 
     *         was not found
     */
    public ImageIcon getIconResource(String resource) {
        return (ImageIcon)get(resource);
    }
    
    /**
     * Return an  ImageIcon given a path to an image
     * 
     * @param resource the path to the image
     * @return the corresponding ImageIcon
     */
    private  static ImageIcon getIcon(String resource) {
        ClassLoader cl = Resources.class.getClassLoader();
        URL r = cl.getResource(resource);

        return new ImageIcon(r != null ?
                             r : cl.getResource(IMAGE_NOT_FOUND));
    }
}
